package com.example.permission.service.impl;

import com.example.common.common.config.filter.UserContext;
import com.example.permission.entity.Permission;
import com.example.permission.entity.SystemRole;
import com.example.permission.mapper.SystemPermissionMapper;
import com.example.permission.mapper.SystemRoleMapper;
import com.example.permission.model.resp.PermissionVO;
import com.example.permission.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/11/1 22:33
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final SystemPermissionMapper systemPermissionMapper;
    private final SystemRoleMapper systemRoleMapper;

    @Override
    public List<PermissionVO> getSystemPermission(String system) {
        // 查询当前用户角色
        SystemRole role = systemRoleMapper.queryRoleByUserId(UserContext.getCurrentUser().getUserId());

        // 查询数据库
        List<Permission> permissions = systemPermissionMapper.getSystemRoot();
        permissions.addAll(systemPermissionMapper.getSystemPermissionByParam(role.getRoleId(), null));
        List<PermissionVO> permissionVOS = convertToTree(permissions);
//        System.out.println(permissionVOS);

        // 构造返回
        return permissionVOS;
    }

    public static List<PermissionVO> convertToTree(List<Permission> permissions) {
        if (permissions == null || permissions.isEmpty()) {
            return Collections.emptyList();
        }

        // 1. 构建映射：permissionId -> PermissionVO
        Map<String, PermissionVO> voMap = new HashMap<>();
        for (Permission p : permissions) {
            PermissionVO vo = new PermissionVO();
            vo.setPermissionId(p.getPermissionId());
            vo.setName(p.getName());
            vo.setPath(p.getPath());
            vo.setRedirect(p.getRedirect());
            vo.setChildren(new ArrayList<>());
            voMap.put(p.getPermissionId(), vo);
        }

        // 2. 先收集所有 redirect != null 的节点作为根节点候选
        List<PermissionVO> roots = new ArrayList<>();
        Set<String> rootIds = new HashSet<>();

        for (Permission p : permissions) {
            if (p.getRedirect() != null) {
                PermissionVO rootVo = voMap.get(p.getPermissionId());
                if (rootVo != null && !roots.contains(rootVo)) {
                    roots.add(rootVo);
                    rootIds.add(p.getPermissionId());
                }
            }
        }

        // 3. 构建父子关系：跳过根节点（redirect != null 的），其余按 parentId 挂载
        for (Permission p : permissions) {
            // 如果已经是根节点，不再挂到其他父节点下
            if (rootIds.contains(p.getPermissionId())) {
                continue;
            }

            String parentId = p.getParentId();
            PermissionVO current = voMap.get(p.getPermissionId());

            if (parentId == null || parentId.isEmpty() || !voMap.containsKey(parentId)) {
                continue;
            }

            PermissionVO parent = voMap.get(parentId);
            parent.getChildren().add(current);
        }

        return roots;
    }
}
